<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>采购物品统计系统</title>
		<!-- 引入Supabase客户端 -->
		<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
		<style>
			* {
				box-sizing: border-box;
				margin: 0;
				padding: 0;
				font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
			}

			body {
				background-color: #f5f7fa;
				color: #333;
				line-height: 1.6;
				height: 100vh;
				overflow: hidden;
				padding: 0;
			}

			/* 登录页面样式 */
			.login-container {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100vh;
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			}

			.login-box {
				background: white;
				padding: 40px;
				border-radius: 10px;
				box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
				width: 100%;
				max-width: 400px;
			}

			.login-title {
				text-align: center;
				margin-bottom: 30px;
				color: #2c3e50;
				font-size: 28px;
			}

			.login-form .form-group {
				margin-bottom: 20px;
			}

			.login-form label {
				display: block;
				margin-bottom: 5px;
				font-weight: 500;
				color: #555;
			}

			.login-form input {
				width: 100%;
				padding: 12px;
				border: 1px solid #ddd;
				border-radius: 4px;
				font-size: 16px;
			}

			.btn-login,
			.btn-register,
			.btn-forgot-password {
				width: 100%;
				padding: 12px;
				border: none;
				border-radius: 4px;
				font-size: 16px;
				cursor: pointer;
				transition: background 0.3s;
				margin-bottom: 10px;
			}

			.btn-login {
				background: #3498db;
				color: white;
			}

			.btn-login:hover {
				background: #2980b9;
			}

			.btn-register {
				background: #2ecc71;
				color: white;
			}

			.btn-register:hover {
				background: #27ae60;
			}

			.btn-forgot-password {
				background: #f39c12;
				color: white;
			}

			.btn-forgot-password:hover {
				background: #e67e22;
			}

			.login-toggle {
				text-align: center;
				margin-top: 20px;
			}

			.toggle-link {
				color: #3498db;
				cursor: pointer;
				text-decoration: underline;
				margin: 0 5px;
			}

			.user-info {
				display: flex;
				align-items: center;
				gap: 10px;
				color: #2c3e50;
				position: relative;
			}

			.user-avatar {
				width: 32px;
				height: 32px;
				border-radius: 50%;
				background: #3498db;
				display: flex;
				align-items: center;
				justify-content: center;
				color: white;
				font-weight: bold;
				cursor: pointer;
			}

			.user-menu {
				position: absolute;
				top: 100%;
				right: 0;
				background: white;
				border-radius: 8px;
				box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
				padding: 10px 0;
				min-width: 150px;
				display: none;
				z-index: 1000;
			}

			.user-menu-item {
				padding: 10px 20px;
				cursor: pointer;
				transition: background 0.3s;
			}

			.user-menu-item:hover {
				background: #f8f9fa;
			}

			.user-menu-item.logout {
				color: #e74c3c;
			}

			.btn-logout {
				background: #e74c3c;
				color: white;
				border: none;
				padding: 8px 15px;
				border-radius: 4px;
				cursor: pointer;
				font-size: 14px;
			}

			.btn-logout:hover {
				background: #c0392b;
			}

			/* 隐藏主应用，直到登录 */
			.app-container {
				display: none;
			}

			.error-message {
				color: #e74c3c;
				font-size: 14px;
				margin-top: 5px;
				text-align: center;
			}

			.success-message {
				color: #2ecc71;
				font-size: 14px;
				margin-top: 5px;
				text-align: center;
			}

			.info-message {
				color: #3498db;
				font-size: 14px;
				margin-top: 5px;
				text-align: center;
			}

			/* 原有样式保持不变 */
			.container {
				height: 100vh;
				background: white;
				display: flex;
				flex-direction: column;
				padding: 20px;
			}

			header {
				text-align: center;
				margin-bottom: 20px;
				padding-bottom: 15px;
				border-bottom: 1px solid #eaeaea;
				display: flex;
				justify-content: space-between;
				align-items: center;
				flex-shrink: 0;
				position: relative;
			}

			h1 {
				color: #2c3e50;
				font-size: 28px;
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
			}

			.header-controls {
				display: flex;
				gap: 15px;
				margin-left: auto;
			}

			.btn-import,
			.btn-export {
				background: #3498db;
				color: white;
				border: none;
				padding: 10px 20px;
				border-radius: 4px;
				cursor: pointer;
				font-size: 16px;
				transition: background 0.3s;
			}

			.btn-import:hover,
			.btn-export:hover {
				background: #2980b9;
			}

			.btn-export {
				background: #2ecc71;
			}

			.btn-export:hover {
				background: #27ae60;
			}

			.btn-delete-all {
				background: #e74c3c;
				color: white;
				border: none;
				padding: 10px 20px;
				border-radius: 4px;
				cursor: pointer;
				font-size: 16px;
				transition: background 0.3s;
			}

			.btn-delete-all:hover {
				background: #c0392b;
			}

			.btn-monthly {
				background: #9b59b6;
				color: white;
				border: none;
				padding: 10px 20px;
				border-radius: 4px;
				cursor: pointer;
				font-size: 16px;
				transition: background 0.3s;
			}

			.btn-monthly:hover {
				background: #8e44ad;
			}

			.stats {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20px;
				flex-wrap: wrap;
				flex-shrink: 0;
			}

			.stat-card {
				background: white;
				border-radius: 8px;
				padding: 15px 20px;
				box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
				flex: 1;
				margin: 0 10px;
				min-width: 200px;
				text-align: center;
			}

			.stat-card h3 {
				font-size: 14px;
				color: #7f8c8d;
				margin-bottom: 8px;
			}

			.stat-value {
				font-size: 24px;
				font-weight: bold;
			}

			.unreimbursed {
				color: #e74c3c;
			}

			.reimbursed {
				color: #2ecc71;
			}

			.content-area {
				display: flex;
				gap: 20px;
				flex: 1;
				min-height: 0;
				overflow: hidden;
			}

			.form-container {
				flex: 0 0 300px;
				background: #f8f9fa;
				padding: 20px;
				border-radius: 8px;
				display: flex;
				flex-direction: column;
				box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
			}

			.form-container h2 {
				margin-bottom: 20px;
				text-align: center;
				color: #2c3e50;
			}

			.form-group {
				margin-bottom: 15px;
			}

			label {
				display: block;
				margin-bottom: 5px;
				font-weight: 500;
				color: #555;
			}

			input,
			select {
				width: 100%;
				padding: 10px;
				border: 1px solid #ddd;
				border-radius: 4px;
				font-size: 16px;
			}

			button {
				background: #3498db;
				color: white;
				border: none;
				padding: 12px 20px;
				border-radius: 4px;
				cursor: pointer;
				font-size: 16px;
				transition: background 0.3s;
			}

			button:hover {
				background: #2980b9;
			}

			.btn-add {
				background: #2ecc71;
				margin-top: 10px;
			}

			.btn-add:hover {
				background: #27ae60;
			}

			.table-container {
				flex: 1;
				background: white;
				border-radius: 8px;
				box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
				display: flex;
				flex-direction: column;
			}

			.table-header {
				padding: 15px;
				border-bottom: 1px solid #eaeaea;
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: white;
				flex-shrink: 0;
			}

			.filter-controls {
				display: flex;
				gap: 10px;
				align-items: center;
				white-space: nowrap;
			}

			.filter-controls select {
				min-width: 140px;
				padding: 8px 12px;
				font-size: 14px;
			}

			.filter-label {
				font-weight: 500;
				color: #555;
			}

			.table-body-container {
				flex: 1;
				overflow: auto;
			}

			table {
				width: 100%;
				border-collapse: collapse;
				min-width: 900px;
			}

			th,
			td {
				padding: 12px 15px;
				text-align: center;
				border-bottom: 1px solid #eaeaea;
			}

			th {
				background-color: #f8f9fa;
				font-weight: 600;
				color: #2c3e50;
				position: sticky;
				top: 0;
			}

			tr:hover {
				background-color: #f8f9fa;
			}

			.status-unreimbursed {
				color: #e74c3c;
				font-weight: 500;
			}

			.status-reimbursed {
				color: #2ecc71;
				font-weight: 500;
			}

			.invoice-checkbox {
				width: 20px;
				height: 20px;
				cursor: pointer;
				accent-color: #2ecc71;
				margin: 0 auto;
				display: block;
			}

			.invoice-received {
				color: #2ecc71;
			}

			.invoice-pending {
				color: #e74c3c;
			}

			.actions {
				display: flex;
				gap: 8px;
				justify-content: center;
			}

			.btn-edit,
			.btn-delete,
			.btn-reimburse {
				padding: 6px 12px;
				font-size: 14px;
				border-radius: 4px;
				cursor: pointer;
				border: none;
				color: white;
			}

			.btn-edit {
				background: #f39c12;
			}

			.btn-edit:hover {
				background: #e67e22;
			}

			.btn-delete {
				background: #e74c3c;
			}

			.btn-delete:hover {
				background: #c0392b;
			}

			.btn-reimburse {
				background: #2ecc71;
			}

			.btn-reimburse:hover {
				background: #27ae60;
			}

			/* 弹窗样式 */
			.modal {
				display: none;
				position: fixed;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-color: rgba(0, 0, 0, 0.5);
				z-index: 1000;
				justify-content: center;
				align-items: center;
			}

			.modal-content {
				background: white;
				border-radius: 10px;
				padding: 30px;
				width: 90%;
				max-width: 500px;
				max-height: 80vh;
				overflow: auto;
				box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
			}

			.modal-header {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-bottom: 20px;
				padding-bottom: 15px;
				border-bottom: 1px solid #eaeaea;
				position: relative;
			}

			.modal-header h2 {
				color: #2c3e50;
			}

			.close-btn {
				background: none;
				border: none;
				font-size: 24px;
				cursor: pointer;
				color: #7f8c8d;
				position: absolute;
				right: 0;
			}

			.monthly-stats-grid {
				display: flex;
				justify-content: space-between;
				gap: 15px;
				margin-bottom: 30px;
			}

			.monthly-card {
				background: #f8f9fa;
				border-radius: 8px;
				padding: 20px;
				text-align: center;
				flex: 1;
				min-width: 0;
			}

			.monthly-card h3 {
				font-size: 14px;
				color: #7f8c8d;
				margin-bottom: 10px;
			}

			.monthly-value {
				font-size: 22px;
				font-weight: bold;
				color: #3498db;
			}

			.monthly-table-container {
				overflow: auto;
			}

			.monthly-table-container table {
				min-width: auto;
				width: 100%;
			}

			/* 导入样式 */
			.import-content {
				display: flex;
				flex-direction: column;
				gap: 25px;
			}

			.import-section {
				padding: 20px;
				background: #f8f9fa;
				border-radius: 8px;
			}

			.import-section h3 {
				color: #2c3e50;
				margin-bottom: 15px;
			}

			.file-input {
				display: none;
			}

			.btn-confirm-import {
				background: #2ecc71;
				margin-top: 15px;
			}

			.btn-confirm-import:hover {
				background: #27ae60;
			}

			.file-info {
				margin-top: 10px;
				font-size: 14px;
				color: #666;
				padding: 8px;
				background: white;
				border-radius: 4px;
				border: 1px solid #ddd;
			}

			.delete-section {
				margin-top: 20px;
				padding: 20px;
				background: #f8f9fa;
				border-radius: 8px;
				border-left: 4px solid #e74c3c;
			}

			.delete-section h3 {
				color: #e74c3c;
				margin-bottom: 10px;
			}

			.delete-section p {
				color: #666;
				margin-bottom: 15px;
				font-size: 14px;
			}

			@media (max-width: 1024px) {
				.content-area {
					flex-direction: column;
				}

				.form-container {
					flex: 0 0 auto;
					margin-bottom: 20px;
				}
			}

			@media (max-width: 768px) {
				header {
					flex-direction: column;
					gap: 15px;
				}

				h1 {
					position: static;
					transform: none;
				}

				.stats {
					flex-direction: column;
				}

				.stat-card {
					margin: 0 0 15px;
				}

				.header-controls {
					width: 100%;
					margin-left: 0;
					flex-direction: column;
				}

				.btn-import,
				.btn-export,
				.btn-delete-all,
				.btn-monthly {
					width: 100%;
					margin-bottom: 10px;
				}

				.actions {
					flex-direction: column;
				}

				.btn-edit,
				.btn-delete,
				.btn-reimburse {
					width: 100%;
				}

				.table-header {
					flex-direction: column;
					gap: 10px;
					align-items: flex-start;
				}

				.filter-controls {
					width: 100%;
				}

				.monthly-stats-grid {
					flex-direction: column;
				}
			}
		</style>
	</head>
	<body>
		<!-- 登录页面 -->
		<div id="login-page" class="login-container">
			<div class="login-box">
				<h2 class="login-title">采购物品统计系统</h2>
				<div id="login-form" class="login-form">
					<div class="form-group">
						<label for="login-email">邮箱</label>
						<input type="email" id="login-email" placeholder="输入邮箱">
					</div>
					<div class="form-group">
						<label for="login-password">密码</label>
						<input type="password" id="login-password" placeholder="输入密码">
					</div>
					<div id="login-error" class="error-message"></div>
					<button class="btn-login" id="btn-login">登录</button>
					<button class="btn-forgot-password" id="btn-forgot-password">忘记密码</button>
					<div class="login-toggle">
						<span>没有账号？</span>
						<span class="toggle-link" id="show-register">立即注册</span>
					</div>
				</div>

				<div id="register-form" class="login-form" style="display: none;">
					<div class="form-group">
						<label for="register-email">邮箱</label>
						<input type="email" id="register-email" placeholder="输入邮箱">
					</div>
					<div class="form-group">
						<label for="register-password">密码</label>
						<input type="password" id="register-password" placeholder="输入密码（至少6位）">
					</div>
					<div id="register-error" class="error-message"></div>
					<div id="register-success" class="success-message"></div>
					<button class="btn-register" id="btn-register">注册</button>
					<div class="login-toggle">
						<span>已有账号？</span>
						<span class="toggle-link" id="show-login">立即登录</span>
					</div>
				</div>

				<!-- 忘记密码表单 -->
				<div id="forgot-password-form" class="login-form" style="display: none;">
					<div class="form-group">
						<label for="forgot-email">邮箱</label>
						<input type="email" id="forgot-email" placeholder="输入注册邮箱">
					</div>
					<div id="forgot-error" class="error-message"></div>
					<div id="forgot-success" class="success-message"></div>
					<button class="btn-forgot-password" id="btn-send-reset">发送重置邮件</button>
					<div class="login-toggle">
						<span class="toggle-link" id="show-login-from-forgot">返回登录</span>
					</div>
				</div>

				<!-- 重置密码表单 -->
				<div id="reset-password-form" class="login-form" style="display: none;">
					<div class="form-group">
						<label for="reset-password">新密码</label>
						<input type="password" id="reset-password" placeholder="输入新密码（至少6位）">
					</div>
					<div class="form-group">
						<label for="reset-confirm-password">确认新密码</label>
						<input type="password" id="reset-confirm-password" placeholder="再次输入新密码">
					</div>
					<div id="reset-error" class="error-message"></div>
					<div id="reset-success" class="success-message"></div>
					<button class="btn-register" id="btn-reset-password">重置密码</button>
					<div class="login-toggle">
						<span class="toggle-link" id="show-login-from-reset">返回登录</span>
					</div>
				</div>
			</div>
		</div>

		<!-- 主应用容器 -->
		<div id="app-container" class="app-container">
			<div class="container">
				<header>
					<h1>采购物品统计系统</h1>
					<div class="user-info">
						<div class="user-avatar" id="user-avatar"></div>
						<span id="user-name">用户</span>
						<div class="user-menu" id="user-menu">
							<div class="user-menu-item" id="btn-change-password">修改密码</div>
							<div class="user-menu-item logout" id="btn-menu-logout">退出登录</div>
						</div>
					</div>
					<div class="header-controls">
						<button class="btn-import" id="btn-import">导入数据</button>
						<button class="btn-export" id="btn-export">导出数据</button>
						<button class="btn-delete-all" id="btn-delete-all">删除筛选数据</button>
						<button class="btn-monthly" id="btn-monthly">月度统计</button>
					</div>
				</header>

				<div class="stats">
					<div class="stat-card">
						<h3>剩余未报销金额</h3>
						<div class="stat-value unreimbursed" id="remaining-amount">¥0.00</div>
					</div>
					<div class="stat-card">
						<h3>剩余待报销数量</h3>
						<div class="stat-value unreimbursed" id="remaining-count">0</div>
					</div>
					<div class="stat-card">
						<h3>总采购金额</h3>
						<div class="stat-value" id="monthly-total-amount">¥0.00</div>
					</div>
				</div>

				<div class="content-area">
					<div class="form-container">
						<h2>新增采购物品</h2>
						<div class="form-group">
							<label for="date">日期</label>
							<input type="date" id="date" required>
						</div>
						<div class="form-group">
							<label for="item-name">物品名称</label>
							<input type="text" id="item-name" placeholder="输入物品名称" required>
						</div>
						<div class="form-group">
							<label for="supplier">供应商</label>
							<input type="text" id="supplier" placeholder="输入供应商名称" required>
						</div>
						<div class="form-group">
							<label for="amount">金额</label>
							<input type="number" id="amount" placeholder="输入金额" min="0" step="0.01" required>
						</div>
						<div class="form-group">
							<label for="reimbursed">报销状态</label>
							<select id="reimbursed">
								<option value="未报销" selected>未报销</option>
								<option value="已报销">已报销</option>
							</select>
						</div>
						<button class="btn-add" id="add-item">添加物品</button>
					</div>

					<div class="table-container">
						<div class="table-header">
							<h3>采购物品列表</h3>
							<div class="filter-controls">
								<select id="month-filter">
									<option value="all">全部月份</option>
								</select>
								<select id="reimbursed-filter">
									<option value="all">全部报销状态</option>
									<option value="已报销">已报销</option>
									<option value="未报销">未报销</option>
								</select>
								<select id="invoice-filter">
									<option value="all">全部发票状态</option>
									<option value="received">已获得</option>
									<option value="pending">未获得</option>
								</select>
							</div>
						</div>
						<div class="table-body-container">
							<table>
								<thead>
									<tr>
										<th>序号</th>
										<th>日期</th>
										<th>物品名称</th>
										<th>供应商</th>
										<th>金额</th>
										<th>报销状态</th>
										<th>发票状态</th>
										<th>操作</th>
									</tr>
								</thead>
								<tbody id="items-table">
									<!-- 动态内容 -->
								</tbody>
							</table>
						</div>
					</div>
				</div>
			</div>

			<!-- 月度统计弹窗 -->
			<div class="modal" id="monthly-modal">
				<div class="modal-content">
					<div class="modal-header">
						<h2>月度统计详情</h2>
						<button class="close-btn" id="close-monthly">&times;</button>
					</div>

					<div class="monthly-stats-grid">
						<div class="monthly-card">
							<h3>总采购金额</h3>
							<div class="monthly-value" id="total-amount">¥0.00</div>
						</div>
						<div class="monthly-card">
							<h3>总采购数量</h3>
							<div class="monthly-value" id="total-count">0</div>
						</div>
						<div class="monthly-card">
							<h3>总未报销金额</h3>
							<div class="monthly-value unreimbursed" id="total-unreimbursed">¥0.00</div>
						</div>
					</div>

					<div class="monthly-table-container">
						<table>
							<thead>
								<tr>
									<th>日期</th>
									<th>采购金额</th>
									<th>采购数量</th>
									<th>未报销金额</th>
								</tr>
							</thead>
							<tbody id="monthly-table">
								<!-- 动态内容 -->
							</tbody>
						</table>
					</div>
				</div>
			</div>

			<!-- 导入数据弹窗 -->
			<div class="modal" id="import-modal">
				<div class="modal-content">
					<div class="modal-header">
						<h2>数据导入</h2>
						<button class="close-btn" id="close-import">&times;</button>
					</div>

					<div class="import-content">
						<div class="import-section">
							<h3>导入数据</h3>
							<p>选择JSON格式的数据文件：</p>
							<input type="file" id="file-input" class="file-input" accept=".json">
							<button class="btn-import" id="select-file">选择文件</button>
							<div id="file-info" class="file-info">未选择文件</div>
							<button class="btn-confirm-import" id="confirm-import" style="display: none;">确认导入</button>
						</div>

						<div class="delete-section">
							<h3>危险操作</h3>
							<p>导入数据将<strong>完全覆盖</strong>当前的所有采购记录，此操作不可撤销。建议在导入前先导出备份当前数据。</p>
						</div>
					</div>
				</div>
			</div>

			<!-- 修改密码弹窗 -->
			<div class="modal" id="change-password-modal">
				<div class="modal-content">
					<div class="modal-header">
						<h2>修改密码</h2>
						<button class="close-btn" id="close-change-password">&times;</button>
					</div>

					<div class="form-group">
						<label for="current-password">当前密码</label>
						<input type="password" id="current-password" placeholder="输入当前密码">
					</div>
					<div class="form-group">
						<label for="new-password">新密码</label>
						<input type="password" id="new-password" placeholder="输入新密码（至少6位）">
					</div>
					<div class="form-group">
						<label for="confirm-new-password">确认新密码</label>
						<input type="password" id="confirm-new-password" placeholder="再次输入新密码">
					</div>
					<div id="change-password-error" class="error-message"></div>
					<div id="change-password-success" class="success-message"></div>
					<button class="btn-add" id="btn-confirm-change-password">确认修改</button>
				</div>
			</div>
		</div>

		<script>
			// Supabase配置
			const SUPABASE_URL = 'https://ieeeerqlnodtxcsbxvtb.supabase.co';
			const SUPABASE_ANON_KEY =
				'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImllZWVlcnFsbm9kdHhjc2J4dnRiIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjEwMDIwMTEsImV4cCI6MjA3NjU3ODAxMX0.fQ7bzpmCxMCHRmuLIPkPhwuZ9oz0hdaNDd1RjmHfq90';

			// 初始化Supabase客户端
			const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

			// 登录相关DOM元素
			const loginPage = document.getElementById('login-page');
			const appContainer = document.getElementById('app-container');
			const loginForm = document.getElementById('login-form');
			const registerForm = document.getElementById('register-form');
			const forgotPasswordForm = document.getElementById('forgot-password-form');
			const resetPasswordForm = document.getElementById('reset-password-form');
			const showRegister = document.getElementById('show-register');
			const showLogin = document.getElementById('show-login');
			const showLoginFromForgot = document.getElementById('show-login-from-forgot');
			const showLoginFromReset = document.getElementById('show-login-from-reset');
			const btnLogin = document.getElementById('btn-login');
			const btnRegister = document.getElementById('btn-register');
			const btnForgotPassword = document.getElementById('btn-forgot-password');
			const btnSendReset = document.getElementById('btn-send-reset');
			const btnResetPassword = document.getElementById('btn-reset-password');
			const userAvatar = document.getElementById('user-avatar');
			const userName = document.getElementById('user-name');
			const userMenu = document.getElementById('user-menu');
			const btnChangePassword = document.getElementById('btn-change-password');
			const btnMenuLogout = document.getElementById('btn-menu-logout');
			const loginError = document.getElementById('login-error');
			const registerError = document.getElementById('register-error');
			const registerSuccess = document.getElementById('register-success');
			const forgotError = document.getElementById('forgot-error');
			const forgotSuccess = document.getElementById('forgot-success');
			const resetError = document.getElementById('reset-error');
			const resetSuccess = document.getElementById('reset-success');

			// 修改密码相关元素
			const changePasswordModal = document.getElementById('change-password-modal');
			const closeChangePassword = document.getElementById('close-change-password');
			const btnConfirmChangePassword = document.getElementById('btn-confirm-change-password');
			const changePasswordError = document.getElementById('change-password-error');
			const changePasswordSuccess = document.getElementById('change-password-success');

			// 原有的全局变量
			let items = [];
			let editIndex = -1;
			let currentFilter = 'all';
			let currentReimbursedFilter = 'all';
			let currentInvoiceFilter = 'all';

			// DOM元素
			const dateInput = document.getElementById('date');
			const itemNameInput = document.getElementById('item-name');
			const supplierInput = document.getElementById('supplier');
			const amountInput = document.getElementById('amount');
			const reimbursedSelect = document.getElementById('reimbursed');
			const addButton = document.getElementById('add-item');
			const itemsTable = document.getElementById('items-table');
			const remainingAmount = document.getElementById('remaining-amount');
			const remainingCount = document.getElementById('remaining-count');
			const monthlyTotalAmount = document.getElementById('monthly-total-amount');
			const monthFilter = document.getElementById('month-filter');
			const reimbursedFilter = document.getElementById('reimbursed-filter');
			const invoiceFilter = document.getElementById('invoice-filter');

			// 月度统计相关元素
			const monthlyModal = document.getElementById('monthly-modal');
			const btnMonthly = document.getElementById('btn-monthly');
			const closeMonthly = document.getElementById('close-monthly');
			const totalAmount = document.getElementById('total-amount');
			const totalCount = document.getElementById('total-count');
			const totalUnreimbursed = document.getElementById('total-unreimbursed');
			const monthlyTable = document.getElementById('monthly-table');

			// 导入导出相关元素
			const importModal = document.getElementById('import-modal');
			const btnImport = document.getElementById('btn-import');
			const btnExport = document.getElementById('btn-export');
			const btnDeleteAll = document.getElementById('btn-delete-all');
			const closeImport = document.getElementById('close-import');
			const fileInput = document.getElementById('file-input');
			const selectFileBtn = document.getElementById('select-file');
			const fileInfo = document.getElementById('file-info');
			const confirmImportBtn = document.getElementById('confirm-import');

			// 设置默认日期为今天
			const today = new Date().toISOString().split('T')[0];
			dateInput.value = today;

			// 切换登录/注册表单
			showRegister.addEventListener('click', () => {
				loginForm.style.display = 'none';
				registerForm.style.display = 'block';
				forgotPasswordForm.style.display = 'none';
				resetPasswordForm.style.display = 'none';
				clearErrors();
			});

			showLogin.addEventListener('click', () => {
				registerForm.style.display = 'none';
				loginForm.style.display = 'block';
				forgotPasswordForm.style.display = 'none';
				resetPasswordForm.style.display = 'none';
				clearErrors();
			});

			showLoginFromForgot.addEventListener('click', () => {
				forgotPasswordForm.style.display = 'none';
				loginForm.style.display = 'block';
				clearErrors();
			});

			showLoginFromReset.addEventListener('click', () => {
				resetPasswordForm.style.display = 'none';
				loginForm.style.display = 'block';
				clearErrors();
			});

			// 忘记密码按钮
			btnForgotPassword.addEventListener('click', () => {
				loginForm.style.display = 'none';
				registerForm.style.display = 'none';
				forgotPasswordForm.style.display = 'block';
				resetPasswordForm.style.display = 'none';
				clearErrors();
			});

			// 用户菜单显示/隐藏
			userAvatar.addEventListener('click', (e) => {
				e.stopPropagation();
				userMenu.style.display = userMenu.style.display === 'block' ? 'none' : 'block';
			});

			// 点击其他地方隐藏用户菜单
			document.addEventListener('click', () => {
				userMenu.style.display = 'none';
			});

			// 修改密码菜单项
			btnChangePassword.addEventListener('click', () => {
				userMenu.style.display = 'none';
				changePasswordModal.style.display = 'flex';
				clearChangePasswordForm();
			});

			// 菜单退出登录
			btnMenuLogout.addEventListener('click', async () => {
				await supabase.auth.signOut();
				showLoginPage();
			});

			// 关闭修改密码弹窗
			closeChangePassword.addEventListener('click', () => {
				changePasswordModal.style.display = 'none';
			});

			// 清除错误信息
			function clearErrors() {
				loginError.textContent = '';
				registerError.textContent = '';
				registerSuccess.textContent = '';
				forgotError.textContent = '';
				forgotSuccess.textContent = '';
				resetError.textContent = '';
				resetSuccess.textContent = '';
			}

			// 清除修改密码表单
			function clearChangePasswordForm() {
				document.getElementById('current-password').value = '';
				document.getElementById('new-password').value = '';
				document.getElementById('confirm-new-password').value = '';
				changePasswordError.textContent = '';
				changePasswordSuccess.textContent = '';
			}

			// 发送密码重置邮件
			btnSendReset.addEventListener('click', async () => {
				const email = document.getElementById('forgot-email').value;

				if (!email) {
					forgotError.textContent = '请输入邮箱地址';
					return;
				}

				try {
					const {
						error
					} = await supabase.auth.resetPasswordForEmail(email, {
						redirectTo: window.location.origin,
					});

					if (error) throw error;

					forgotSuccess.textContent = '重置密码邮件已发送，请检查您的邮箱。';
					forgotError.textContent = '';
				} catch (error) {
					forgotError.textContent = '发送失败: ' + error.message;
					forgotSuccess.textContent = '';
				}
			});

			// 重置密码
			btnResetPassword.addEventListener('click', async () => {
				const newPassword = document.getElementById('reset-password').value;
				const confirmPassword = document.getElementById('reset-confirm-password').value;

				if (!newPassword || !confirmPassword) {
					resetError.textContent = '请填写所有字段';
					return;
				}

				if (newPassword.length < 6) {
					resetError.textContent = '密码至少需要6位';
					return;
				}

				if (newPassword !== confirmPassword) {
					resetError.textContent = '两次输入的密码不一致';
					return;
				}

				try {
					const {
						error
					} = await supabase.auth.updateUser({
						password: newPassword
					});

					if (error) throw error;

					resetSuccess.textContent = '密码重置成功！';
					resetError.textContent = '';

					// 3秒后跳转到登录页面
					setTimeout(() => {
						resetPasswordForm.style.display = 'none';
						loginForm.style.display = 'block';
						clearErrors();
					}, 2000);
				} catch (error) {
					resetError.textContent = '重置失败: ' + error.message;
					resetSuccess.textContent = '';
				}
			});

			// 修改密码
			btnConfirmChangePassword.addEventListener('click', async () => {
				const currentPassword = document.getElementById('current-password').value;
				const newPassword = document.getElementById('new-password').value;
				const confirmPassword = document.getElementById('confirm-new-password').value;

				if (!currentPassword || !newPassword || !confirmPassword) {
					changePasswordError.textContent = '请填写所有字段';
					return;
				}

				if (newPassword.length < 6) {
					changePasswordError.textContent = '新密码至少需要6位';
					return;
				}

				if (newPassword !== confirmPassword) {
					changePasswordError.textContent = '两次输入的新密码不一致';
					return;
				}

				try {
					// 1. 获取当前用户信息
					const {
						data: {
							user
						},
						error: userError
					} = await supabase.auth.getUser();
					if (!user || userError) {
						throw new Error('用户未登录或登录已过期');
					}

					// 2. 验证当前密码是否正确 - 关键修复！
					const {
						error: signInError
					} = await supabase.auth.signInWithPassword({
						email: user.email,
						password: currentPassword
					});

					if (signInError) {
						throw new Error('当前密码错误，请重新输入');
					}

					// 3. 当前密码验证通过，更新密码
					const {
						error: updateError
					} = await supabase.auth.updateUser({
						password: newPassword
					});

					if (updateError) throw updateError;

					changePasswordSuccess.textContent = '密码修改成功！';
					changePasswordError.textContent = '';

					// 3秒后关闭弹窗
					setTimeout(() => {
						changePasswordModal.style.display = 'none';
						clearChangePasswordForm();
					}, 3000);

				} catch (error) {
					console.error('修改密码错误:', error);
					changePasswordError.textContent = '修改失败: ' + error.message;
					changePasswordSuccess.textContent = '';
				}
			});

			// 用户注册 - 简化版本
			btnRegister.addEventListener('click', async () => {
				const email = document.getElementById('register-email').value;
				const password = document.getElementById('register-password').value;

				if (!email || !password) {
					registerError.textContent = '请填写邮箱和密码';
					return;
				}

				if (password.length < 6) {
					registerError.textContent = '密码至少需要6位';
					return;
				}

				try {
					// 简化注册，不使用任何额外数据
					const {
						data,
						error
					} = await supabase.auth.signUp({
						email,
						password
					});

					if (error) {
						// 检查是否是邮箱验证相关的错误
						if (error.message.includes('email confirmation') || error.message.includes('confirm')) {
							registerSuccess.textContent = '注册成功！请检查您的邮箱验证邮件。';
							registerError.textContent = '';
							// 3秒后切换到登录表单
							setTimeout(() => {
								showLogin.click();
							}, 3000);
						} else {
							throw error;
						}
					} else if (data.user) {
						registerSuccess.textContent = '注册成功！您现在可以登录了。';
						registerError.textContent = '';
						// 3秒后切换到登录表单
						setTimeout(() => {
							showLogin.click();
						}, 3000);
					}
				} catch (error) {
					console.error('注册错误:', error);
					// 提供更友好的错误信息
					if (error.message.includes('Database error saving new user')) {
						registerError.textContent = '注册失败：数据库配置问题。请检查Supabase项目设置。';
					} else if (error.message.includes('User already registered')) {
						registerError.textContent = '该邮箱已被注册，请使用其他邮箱或直接登录。';
					} else {
						registerError.textContent = '注册失败: ' + error.message;
					}
				}
			});

			// 用户登录
			btnLogin.addEventListener('click', async () => {
				const email = document.getElementById('login-email').value;
				const password = document.getElementById('login-password').value;

				if (!email || !password) {
					loginError.textContent = '请填写邮箱和密码';
					return;
				}

				try {
					const {
						data,
						error
					} = await supabase.auth.signInWithPassword({
						email,
						password
					});

					if (error) throw error;

					if (data.user) {
						await loadUserProfile(data.user);
						showApp();
					}
				} catch (error) {
					if (error.message.includes('Invalid login credentials')) {
						loginError.textContent = '邮箱或密码错误，请重试。';
					} else {
						loginError.textContent = error.message;
					}
				}
			});

			// 显示主应用
			function showApp() {
				loginPage.style.display = 'none';
				appContainer.style.display = 'block';
				loadUserData();
			}

			// 显示登录页面
			function showLoginPage() {
				loginPage.style.display = 'flex';
				appContainer.style.display = 'none';
				items = [];
				renderTable();
				updateStats();
			}

			// 加载用户配置
			async function loadUserProfile(user) {
				const displayName = user.email?.split('@')[0] || '用户';
				userName.textContent = displayName;
				userAvatar.textContent = displayName.charAt(0).toUpperCase();
			}

			// 加载用户数据
			async function loadUserData() {
				const {
					data: {
						user
					}
				} = await supabase.auth.getUser();
				if (user) {
					try {
						const {
							data,
							error
						} = await supabase
							.from('procurement_items')
							.select('*')
							.eq('user_id', user.id)
							.order('date', {
								ascending: false
							});

						if (error) {
							console.error('加载数据失败:', error);
							items = [];
						} else {
							// 转换数据格式以兼容原有代码
							items = data.map(item => ({
								date: item.date,
								name: item.name,
								supplier: item.supplier,
								amount: item.amount.toString(),
								reimbursed: item.reimbursed,
								invoiceReceived: item.invoice_received
							}));
						}

						updateMonthFilterOptions();
						renderTable();
						updateStats();
					} catch (error) {
						console.error('加载数据时发生错误:', error);
						items = [];
						updateMonthFilterOptions();
						renderTable();
						updateStats();
					}
				}
			}

			// 保存数据到Supabase
			async function saveItems() {
				const {
					data: {
						user
					}
				} = await supabase.auth.getUser();
				if (!user) return;

				try {
					// 删除用户的所有现有数据
					const {
						error: deleteError
					} = await supabase
						.from('procurement_items')
						.delete()
						.eq('user_id', user.id);

					if (deleteError) {
						console.error('删除旧数据失败:', deleteError);
					}

					// 插入新数据
					if (items.length > 0) {
						const itemsToInsert = items.map(item => ({
							user_id: user.id,
							date: item.date,
							name: item.name,
							supplier: item.supplier,
							amount: parseFloat(item.amount),
							reimbursed: item.reimbursed,
							invoice_received: item.invoiceReceived
						}));

						const {
							error: insertError
						} = await supabase
							.from('procurement_items')
							.insert(itemsToInsert);

						if (insertError) {
							console.error('保存数据失败:', insertError);
							throw insertError;
						}
					}
				} catch (error) {
					console.error('保存数据时发生错误:', error);
					throw error;
				}
			}

			// 修改原有的数据保存函数
			function updateLocalStorage() {
				saveItems().catch(error => {
					console.error('保存到数据库失败:', error);
					alert('保存数据失败，请检查网络连接或刷新页面重试。');
				});
			}

			// 初始化应用
			async function init() {
				// 检查当前登录状态
				const {
					data: {
						session
					}
				} = await supabase.auth.getSession();

				if (session?.user) {
					await loadUserProfile(session.user);
					showApp();
				} else {
					showLoginPage();
				}

				// 原有的初始化代码
				updateMonthFilterOptions();
				renderTable();
				updateStats();

				// 设置事件监听器
				monthFilter.addEventListener('change', function() {
					currentFilter = this.value;
					renderTable();
					updateStats();
				});

				reimbursedFilter.addEventListener('change', function() {
					currentReimbursedFilter = this.value;
					renderTable();
					updateStats();
				});

				invoiceFilter.addEventListener('change', function() {
					currentInvoiceFilter = this.value;
					renderTable();
					updateStats();
				});

				setupImportExportEvents();

				// 检查URL中是否有重置密码的token
				checkResetPasswordToken();
			}

			// 检查重置密码token
			async function checkResetPasswordToken() {
				const urlParams = new URLSearchParams(window.location.hash.substring(1));
				const type = urlParams.get('type');
				const accessToken = urlParams.get('access_token');

				if (type === 'recovery' && accessToken) {
					// 显示重置密码表单
					loginForm.style.display = 'none';
					registerForm.style.display = 'none';
					forgotPasswordForm.style.display = 'none';
					resetPasswordForm.style.display = 'block';

					// 清除URL中的token参数
					window.history.replaceState({}, document.title, window.location.pathname);
				}
			}

			// 监听认证状态变化
			supabase.auth.onAuthStateChange(async (event, session) => {
				if (event === 'SIGNED_IN' && session?.user) {
					await loadUserProfile(session.user);
					showApp();
				} else if (event === 'SIGNED_OUT') {
					showLoginPage();
				} else if (event === 'PASSWORD_RECOVERY') {
					// 显示重置密码表单
					loginForm.style.display = 'none';
					registerForm.style.display = 'none';
					forgotPasswordForm.style.display = 'none';
					resetPasswordForm.style.display = 'block';
				}
			});

			// 设置导入导出事件监听
			function setupImportExportEvents() {
				// 导入按钮点击
				btnImport.addEventListener('click', function() {
					resetImportForm();
					importModal.style.display = 'flex';
				});

				// 导出按钮点击
				btnExport.addEventListener('click', function() {
					exportData();
				});

				// 删除筛选数据按钮点击
				btnDeleteAll.addEventListener('click', function() {
					deleteFilteredData();
				});

				// 关闭导入弹窗
				closeImport.addEventListener('click', function() {
					importModal.style.display = 'none';
				});

				// 选择文件按钮
				selectFileBtn.addEventListener('click', function() {
					fileInput.click();
				});

				// 文件选择变化
				fileInput.addEventListener('change', function(e) {
					const file = e.target.files[0];
					if (file) {
						fileInfo.textContent = `已选择文件: ${file.name} (${(file.size / 1024).toFixed(2)} KB)`;
						confirmImportBtn.style.display = 'block';
					}
				});

				// 确认导入
				confirmImportBtn.addEventListener('click', function() {
					importData();
				});

				// 跟踪鼠标状态
				let mouseDownTarget = null;

				// 记录鼠标按下的目标
				document.addEventListener('mousedown', function(event) {
					mouseDownTarget = event.target;
				});

				// 只在鼠标按下和释放的目标相同时关闭弹窗
				document.addEventListener('mouseup', function(event) {
					// 检查鼠标按下和释放是否在同一个元素上
					if (mouseDownTarget === event.target) {
						const isImportModalBg = event.target === importModal;
						const isMonthlyModalBg = event.target === monthlyModal;
						const isChangePasswordModalBg = event.target === changePasswordModal;

						if (isChangePasswordModalBg) {
							const hasMessages = changePasswordError.textContent || changePasswordSuccess.textContent;
							if (!hasMessages) {
								changePasswordModal.style.display = 'none';
								clearChangePasswordForm();
							}
						} else if (isImportModalBg) {
							importModal.style.display = 'none';
						} else if (isMonthlyModalBg) {
							monthlyModal.style.display = 'none';
						}
					}

					mouseDownTarget = null;
				});

				// 阻止弹窗内容区域的事件
				document.querySelectorAll('.modal-content').forEach(content => {
					content.addEventListener('mousedown', function(event) {
						event.stopPropagation();
					});
					content.addEventListener('mouseup', function(event) {
						event.stopPropagation();
					});
				});

				// 月度统计弹窗
				btnMonthly.addEventListener('click', function() {
					updateMonthlyStats();
					monthlyModal.style.display = 'flex';
				});

				closeMonthly.addEventListener('click', function() {
					monthlyModal.style.display = 'none';
				});
			}

			// 导入数据
			function importData() {
				const file = fileInput.files[0];
				if (!file) {
					alert('请先选择文件！');
					return;
				}

				const reader = new FileReader();
				reader.onload = function(e) {
					try {
						const importedData = JSON.parse(e.target.result);

						// 验证数据格式
						if (!Array.isArray(importedData)) {
							throw new Error('数据格式不正确：应为数组格式');
						}

						// 验证每个项目的结构
						const isValid = importedData.every(item =>
							item &&
							typeof item.date === 'string' &&
							typeof item.name === 'string' &&
							typeof item.supplier === 'string' &&
							typeof item.amount === 'string' &&
							typeof item.reimbursed === 'string'
						);

						if (!isValid) {
							throw new Error('数据格式不正确：缺少必要字段');
						}

						if (confirm(`确定要导入 ${importedData.length} 条记录吗？这将覆盖现有数据。`)) {
							// 确保导入的数据有invoiceReceived字段
							const processedData = importedData.map(item => {
								if (item.invoiceReceived === undefined) {
									item.invoiceReceived = false;
								}
								return item;
							});

							items = processedData;
							updateLocalStorage();

							// 更新UI
							updateMonthFilterOptions();
							renderTable();
							updateStats();

							alert(`成功导入 ${importedData.length} 条记录！`);
							importModal.style.display = 'none';
							resetImportForm();
						}
					} catch (error) {
						alert('导入失败：' + error.message);
					}
				};
				reader.readAsText(file);
			}

			// 导出数据
			function exportData() {
				if (items.length === 0) {
					alert('没有数据可以导出！');
					return;
				}

				const dataStr = JSON.stringify(items, null, 2);
				const dataBlob = new Blob([dataStr], {
					type: 'application/json'
				});

				// 创建下载链接
				const url = URL.createObjectURL(dataBlob);
				const link = document.createElement('a');
				link.href = url;

				// 生成文件名（包含当前日期）
				const now = new Date();
				const dateStr = now.toISOString().split('T')[0];
				link.download = `采购数据_${dateStr}.json`;

				// 触发下载
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
				URL.revokeObjectURL(url);

				alert(`成功导出 ${items.length} 条记录！`);
			}

			// 删除筛选后的数据
			function deleteFilteredData() {
				const filteredItems = getFilteredItems();

				if (filteredItems.length === 0) {
					alert('当前筛选条件下没有数据可以删除！');
					return;
				}

				let message = '';
				if (currentFilter === 'all' && currentReimbursedFilter === 'all' && currentInvoiceFilter === 'all') {
					message = `确定要删除所有 ${filteredItems.length} 条采购记录吗？此操作不可撤销！`;
				} else {
					message = `确定要删除当前筛选条件下的 ${filteredItems.length} 条采购记录吗？此操作不可撤销！`;
				}

				if (confirm(message)) {
					// 从原始数据中删除筛选出的项目
					items = items.filter(item => {
						// 检查月份筛选
						if (currentFilter !== 'all') {
							const itemDate = new Date(item.date);
							const itemMonth =
								`${itemDate.getFullYear()}-${(itemDate.getMonth() + 1).toString().padStart(2, '0')}`;
							if (itemMonth !== currentFilter) {
								return true;
							}
						}

						// 检查报销状态筛选
						if (currentReimbursedFilter !== 'all' && item.reimbursed !== currentReimbursedFilter) {
							return true;
						}

						// 检查发票状态筛选
						if (currentInvoiceFilter !== 'all') {
							const invoiceMatch = (currentInvoiceFilter === 'received') ?
								item.invoiceReceived : !item.invoiceReceived;
							if (!invoiceMatch) {
								return true;
							}
						}

						return false;
					});

					// 保存到数据库
					updateLocalStorage();

					// 更新UI
					updateMonthFilterOptions();
					renderTable();
					updateStats();

					alert(`成功删除 ${filteredItems.length} 条记录！`);
				}
			}

			// 重置导入表单
			function resetImportForm() {
				fileInput.value = '';
				fileInfo.textContent = '未选择文件';
				confirmImportBtn.style.display = 'none';
			}

			// 更新月份筛选选项
			function updateMonthFilterOptions() {
				// 获取所有存在的月份
				const months = new Set();
				items.forEach(item => {
					const itemDate = new Date(item.date);
					const year = itemDate.getFullYear();
					const month = itemDate.getMonth() + 1;
					const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
					months.add(monthKey);
				});

				// 清空现有选项（保留"全部月份"）
				monthFilter.innerHTML = '<option value="all">全部月份</option>';

				// 添加存在的月份选项
				const sortedMonths = Array.from(months).sort((a, b) => b.localeCompare(a));
				sortedMonths.forEach(month => {
					const [year, monthNum] = month.split('-');
					const option = document.createElement('option');
					option.value = month;
					option.textContent = `${year}年${parseInt(monthNum)}月`;
					monthFilter.appendChild(option);
				});
			}

			// 获取筛选后的物品列表
			function getFilteredItems() {
				let filteredItems = [...items];

				// 月份筛选
				if (currentFilter !== 'all') {
					filteredItems = filteredItems.filter(item => {
						const itemDate = new Date(item.date);
						const itemMonth =
							`${itemDate.getFullYear()}-${(itemDate.getMonth() + 1).toString().padStart(2, '0')}`;
						return itemMonth === currentFilter;
					});
				}

				// 报销状态筛选
				if (currentReimbursedFilter !== 'all') {
					filteredItems = filteredItems.filter(item => item.reimbursed === currentReimbursedFilter);
				}

				// 发票状态筛选
				if (currentInvoiceFilter !== 'all') {
					filteredItems = filteredItems.filter(item => {
						if (currentInvoiceFilter === 'received') {
							return item.invoiceReceived === true;
						} else if (currentInvoiceFilter === 'pending') {
							return item.invoiceReceived === false;
						}
						return true;
					});
				}

				return filteredItems.sort((a, b) => new Date(a.date) - new Date(b.date));
			}

			// 渲染表格
			function renderTable() {
				itemsTable.innerHTML = '';

				const filteredItems = getFilteredItems();

				if (filteredItems.length === 0) {
					itemsTable.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无数据，请添加采购物品</td></tr>';
					return;
				}

				filteredItems.forEach((item, index) => {
					const row = document.createElement('tr');

					// 根据报销状态设置颜色
					const statusClass = item.reimbursed === '已报销' ? 'status-reimbursed' : 'status-unreimbursed';

					row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${item.date}</td>
                    <td>${item.name}</td>
                    <td>${item.supplier}</td>
                    <td>¥${parseFloat(item.amount).toFixed(2)}</td>
                    <td class="${statusClass}">${item.reimbursed}</td>
                    <td>
                        <input type="checkbox" class="invoice-checkbox" ${item.invoiceReceived ? 'checked' : ''} 
                               onchange="toggleInvoiceReceived(${items.indexOf(item)})">
                    </td>
                    <td>
                        <div class="actions">
                            <button class="btn-reimburse" onclick="toggleReimbursed(${items.indexOf(item)})">${item.reimbursed === '已报销' ? '标记未报销' : '标记已报销'}</button>
                            <button class="btn-edit" onclick="editItem(${items.indexOf(item)})">编辑</button>
                            <button class="btn-delete" onclick="deleteItem(${items.indexOf(item)})">删除</button>
                        </div>
                    </td>
                `;

					itemsTable.appendChild(row);
				});
			}

			// 切换发票状态
			function toggleInvoiceReceived(index) {
				items[index].invoiceReceived = !items[index].invoiceReceived;
				updateLocalStorage();
				renderTable();
			}

			// 更新统计信息
			function updateStats() {
				const filteredItems = getFilteredItems();

				let unreimbursedTotal = 0;
				let unreimbursedCount = 0;
				let monthlyTotal = 0;

				filteredItems.forEach(item => {
					const amount = parseFloat(item.amount);
					monthlyTotal += amount;

					if (item.reimbursed === '未报销') {
						unreimbursedTotal += amount;
						unreimbursedCount++;
					}
				});

				monthlyTotalAmount.textContent = `¥${monthlyTotal.toFixed(2)}`;
				remainingAmount.textContent = `¥${unreimbursedTotal.toFixed(2)}`;
				remainingCount.textContent = unreimbursedCount;
			}

			// 更新月度统计信息
			function updateMonthlyStats() {
				// 总统计数据（所有物品）
				let allTotal = 0;
				let allUnreimbursedTotal = 0;
				let allItemCount = 0;

				items.forEach(item => {
					const amount = parseFloat(item.amount);
					allTotal += amount;
					allItemCount++;

					if (item.reimbursed === '未报销') {
						allUnreimbursedTotal += amount;
					}
				});

				totalAmount.textContent = `¥${allTotal.toFixed(2)}`;
				totalCount.textContent = allItemCount;
				totalUnreimbursed.textContent = `¥${allUnreimbursedTotal.toFixed(2)}`;

				// 生成月度统计表格
				generateMonthlyTable();
			}

			// 生成月度统计表格
			function generateMonthlyTable() {
				monthlyTable.innerHTML = '';

				// 获取所有数据中的最小和最大月份
				let minDate = new Date();
				let maxDate = new Date(2025, 9, 1); // 2025年10月作为起始点

				if (items.length > 0) {
					// 找到数据中的最早日期和最晚日期
					const dates = items.map(item => new Date(item.date));
					minDate = new Date(Math.min(...dates));
					maxDate = new Date(Math.max(...dates));

					// 确保起始日期不早于2025年10月
					const startDate = new Date(2025, 9, 1); // 2025年10月
					if (minDate > startDate) {
						minDate = startDate;
					}
				}

				const monthlyData = {};

				// 生成从最小月份到最大月份的月份列表
				for (let date = new Date(minDate); date <= maxDate; date.setMonth(date.getMonth() + 1)) {
					const year = date.getFullYear();
					const month = date.getMonth() + 1;
					const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
					monthlyData[monthKey] = {
						date: `${year}年${month}月`,
						totalAmount: 0,
						itemCount: 0,
						unreimbursedAmount: 0
					};
				}

				// 填充月度数据
				items.forEach(item => {
					const itemDate = new Date(item.date);
					const year = itemDate.getFullYear();
					const month = itemDate.getMonth() + 1;
					const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
					const amount = parseFloat(item.amount);

					if (monthlyData[monthKey]) {
						monthlyData[monthKey].totalAmount += amount;
						monthlyData[monthKey].itemCount += 1;

						if (item.reimbursed === '未报销') {
							monthlyData[monthKey].unreimbursedAmount += amount;
						}
					}
				});

				// 生成表格行
				Object.values(monthlyData).forEach(data => {
					const row = document.createElement('tr');
					row.innerHTML = `
                    <td>${data.date}</td>
                    <td>¥${data.totalAmount.toFixed(2)}</td>
                    <td>${data.itemCount}</td>
                    <td>¥${data.unreimbursedAmount.toFixed(2)}</td>
                `;
					monthlyTable.appendChild(row);
				});
			}

			// 添加或更新物品
			addButton.addEventListener('click', function() {
				const date = dateInput.value;
				const name = itemNameInput.value.trim();
				const supplier = supplierInput.value.trim();
				const amount = amountInput.value;
				const reimbursed = reimbursedSelect.value;

				if (!date || !name || !supplier || !amount) {
					alert('请填写所有字段！');
					return;
				}

				if (editIndex === -1) {
					// 添加新物品
					const newItem = {
						date,
						name,
						supplier,
						amount,
						reimbursed,
						invoiceReceived: false
					};

					items.push(newItem);
				} else {
					// 更新现有物品
					items[editIndex] = {
						date,
						name,
						supplier,
						amount,
						reimbursed,
						invoiceReceived: items[editIndex].invoiceReceived
					};

					// 重置编辑状态
					editIndex = -1;
					addButton.textContent = '添加物品';
				}

				// 保存到数据库
				updateLocalStorage();

				// 更新UI
				updateMonthFilterOptions();
				renderTable();
				updateStats();

				// 重置表单
				resetForm();
			});

			// 编辑物品
			function editItem(index) {
				const item = items[index];

				// 填充表单
				dateInput.value = item.date;
				itemNameInput.value = item.name;
				supplierInput.value = item.supplier;
				amountInput.value = item.amount;
				reimbursedSelect.value = item.reimbursed;

				// 设置编辑状态
				editIndex = index;
				addButton.textContent = '更新物品';
			}

			// 删除物品
			function deleteItem(index) {
				if (confirm('确定要删除这个物品吗？')) {
					items.splice(index, 1);
					updateLocalStorage();

					// 更新UI
					updateMonthFilterOptions();
					renderTable();
					updateStats();
				}
			}

			// 切换报销状态
			function toggleReimbursed(index) {
				items[index].reimbursed = items[index].reimbursed === '已报销' ? '未报销' : '已报销';
				updateLocalStorage();
				renderTable();
				updateStats();
			}

			// 重置表单
			function resetForm() {
				dateInput.value = today;
				itemNameInput.value = '';
				supplierInput.value = '';
				amountInput.value = '';
				reimbursedSelect.value = '未报销';
				editIndex = -1;
				addButton.textContent = '添加物品';
			}

			// 启动应用
			init();
		</script>
	</body>
</html>